package bounjour;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

abstract class IObjectFactory {
	
	static Connection getConnection() throws Exception {
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		return DriverManager.getConnection(
	              "jdbc:mysql://vault103.com/rasputin_bounjour",
	              "rasputin_bounadm","b0unj0ur$");
		
		//return DriverManager.getConnection(
	    //          "jdbc:mysql://localhost/bounjour",
	    //          "spring2011g2","spring2011g2pass");
	}
	
	static <T extends IObjectFactory> T getSingleObject(Class<T> c, String sqlstr, Object... parameters) {
		Connection cn;
	    PreparedStatement st;
	    T obj = null;
	    try{
	    	cn = getConnection();
	    	st = cn.prepareStatement(sqlstr);
	    	if (parameters != null)
	    		for (int i=0; i<parameters.length; i++) st.setObject(i+1, parameters[i]);
	    	
	    	ResultSet RS = st.executeQuery();
	    	if (RS.next()){
	    		obj = c.newInstance();
	    		obj.buildFromReader(RS);
	    	}
	    	RS.close();
	    	cn.close();
	    	
	    }
	    catch (Exception sqlEx){
	      System.err.println(sqlEx);
	    }
	    return obj;
	}
	
	static <T extends IObjectFactory> List<T> getObjectList(Class<T> c, String sqlstr, Object... parameters) {
		Connection cn;
	    PreparedStatement st;
	    List<T> list = new ArrayList<T>();
	    try{
	    	cn = getConnection();
	    	st = cn.prepareStatement(sqlstr);
	    	if (parameters != null)
	    		for (int i=0; i<parameters.length; i++) st.setObject(i+1, parameters[i]);
	    	ResultSet RS = st.executeQuery();
	    	while (RS.next()){
	    		T obj = c.newInstance();
	    		obj.buildFromReader(RS);
	    		list.add(obj);
	    	}
	    	RS.close();
	    	cn.close();
	    }
	    catch (Exception sqlEx){
	      System.err.println(sqlEx);
	    }
	    return list;
	}
	
	abstract void buildFromReader(java.sql.ResultSet RS);
}
